<?php
	require_once("config.php");

    if (AuthManager::AuthLevelMatches(array(AuthConstants::ADMINISTRATORS, AuthConstants::LANDLORDS))) {
	    $menu = new Menu("Other Actions");
	    $menu->AddItem(new MenuItem("Edit Profile","profile.php?action=edit&id=" . $_GET['id']),array(AuthConstants::ADMINISTRATORS, AuthConstants::LANDLORDS));
	    MenuManager::AddMenu("View Profile",$menu);
	}
	else {
        $menu = new Menu("Other Actions");
        $menu->AddItem(new MenuItem("View Profile","profile.php" . (isset($_GET['id']) ? "?id=" . $_GET['id'] : "?id=" . AuthManager::GetUserID()) , AuthConstants::ALL_LOGGED_IN));
        MenuManager::AddMenu("Edit Your Profile",$menu);    
	}
	
	if ($_POST) {
        echo "<pre>" . print_r($_POST,true) . "</pre>";
        echo "<pre>" . print_r($_FILES,true) . "</pre>";

        if (strpos($_POST['website'],"http://") === false)
            $_POST['website'] = "http://" . $_POST['website'];
            
		$create = array(
			"accountid"		=> $_POST['landlordid'],
			"address_line1" => $_POST['address_line1'],
			"address_line2" => $_POST['address_line2'],
			"city"			=> $_POST['city'],
			"state"			=> $_POST['state'],
			"zip"			=> $_POST['zip'],
			"office_phone"	=> $_POST['office_phone'],
			"cell_phone"	=> $_POST['cell_phone'],
			"website"		=> $_POST['website'],
			"other"			=> $_POST['other']
		);
		$query = "";
		if (isset($_POST['id'])) $query = QueryTools::CreateQuery($create, "landlords", "update", $_POST['id']);
		else $query = QueryTools::CreateQuery($create, "landlords");
		
		DBM::Execute($query);
		
		if (isset($_FILES)) {
			foreach ($_FILES as $uploaded) {
				switch ($uploaded['error']) {
					case UPLOAD_ERR_OK:
						$ext = explode(".",$uploaded['name']);
						$ext = strtolower(array_pop($ext));
						if ($ext == "jpg" || $ext == "jpeg" || $ext == "png" || $ext == "gif") {
							echo "Trying to move $uploaded[tmp_name] to listingimages/landlords/" . $create['accountid'] . "." . $ext . " ... ";
                            if (!file_exists($uploaded['tmp_name'])) echo "<b>TEMP FILE DOES NOT EXIST</b><br />";
							if (move_uploaded_file($uploaded['tmp_name'], "listingimages/landlords/" . $create['accountid'] . ".$ext")) {
								$thumb = new Thumbnail("listingimages/landlords/$create[accountid].$ext",NULL,NULL,RESOURCE);
								$resource = $thumb->Render();
								imagepng($resource,"listingimages/landlords/$create[accountid].png");
                            }
							else
								echo "FAIL<br />";
						}
						else {
							// err
						}
					break;
					case UPLOAD_ERR_INI_SIZE:
					break;
					case UPLOAD_ERR_FORM_SIZE:
					break;
					case UPLOAD_ERR_PARTIAL:
					break;
					case UPLOAD_ERR_NO_TMP_DIR:
					break;
					case UPLOAD_ERR_CANT_WRITE:
					break;
					default: // 4
						// no upload
				}			
			}
		}
		
		header("Location: profile.php?action=edit&saved=1&id=" . $_POST['landlordid']);
		exit;
	}
	else if ($_GET['action'] == 'edit') {
        $landlordid = AuthManager::GetUserID();
            if (AuthManager::AuthLevelMatches(AuthConstants::ADMINISTRATORS))
                $landlordid = (isset($_GET['id']) ? $_GET['id'] : NULL);
                
        $menu = new Menu("Profile Actions");
        $menu->AddItem(new MenuItem("View Profile","profile.php?id=$landlordid"));
        MenuManager::AddMenu("Edit Your Profile",$menu);
	
		Functions::PrintHeader("Edit Your Profile");
		if (AuthManager::AuthLevelMatches(array(AuthConstants::LANDLORDS, AuthConstants::ADMINISTRATORS))) {
            if (is_null($landlordid)) {
                WarningMessage::Show("No ID Specified","You havent specified a profile to edit.");
            }
            else {
                $query = "SELECT *,landlords.id as profileid FROM landlords JOIN guests ON guests.id=landlords.accountid WHERE accountid=$landlordid;";
                $profile = DBM::FetchRow($query);
                ?><form method="POST" action="profile.php" enctype="multipart/form-data"><?php
                if (is_array($profile))
                    echo "<input type='hidden' name='id' value='$profile[profileid]' />";
                echo "<input type='hidden' name='landlordid' value='$landlordid' />";
                
                if (isset($_GET['saved']))
                    SuccessMessage::Show("Profile Saved!","Your profile has been saved.  Now, <a href='listing.php'>start adding listings</a><br />");
                ?>
                <table class='wide cgltable'>
                    <tr>
                        <th colspan='3'>Your Profile</th>
                    </tr>
                    <tr>	
                        <td rowspan='10' align='center'>
                            <div style='text-align:center;'>
                                <?php
                                    $thumb = new Thumbnail("listingimages/landlords/$landlordid.png",NULL,300);
                                    $thumb->Render();
                                ?>
                            </div>
                            <hr />
                            <fieldset>
                                <legend>Change Photo</legend>
                                <input type='file' name='landlord_photo' /><br />
                                <i>Click 'Save' in the bottom right to save the change</i>						
                            </fieldset>
                            <br />
                        </td>
                        <td>Address</td>
                        <td>
                            <input type='text' name='address_line1' value="<? echo $profile['address_line1']; ?>" />
                        </td>
                    </tr>
                    <tr>
                        <td>Apt./Room #</td>
                        <td><input type='text' name='address_line2' value="<? echo $profile['address_line2']; ?>" /></td>
                    </tr>
                    <tr>
                        <td>City</td>
                        <td><input type='text' name='city' value="<? echo $profile['city']; ?>" /></td>
                    </tr>
                    <tr>
                        <td>State</td>
                        <td>
                        <?php
                            echo "<select name='state'>";
                                    $states = array(
                                        "AL" => "ALABAMA",
                                        "AK" => "ALASKA",
                                        "AS" => "AMERICAN SAMOA",
                                        "AZ" => "ARIZONA",
                                        "AR" => "ARKANSAS",
                                        "CA" => "CALIFORNIA",
                                        "CO" => "COLORADO",
                                        "CT" => "CONNECTICUT",
                                        "DE" => "DELAWARE",
                                        "DC" => "DISTRICT OF COLUMBIA",
                                        "FM" => "FEDERATED STATES OF MICRONESIA",
                                        "FL" => "FLORIDA",
                                        "GA" => "GEORGIA",
                                        "GU" => "GUAM",
                                        "HI" => "HAWAII",
                                        "ID" => "IDAHO",
                                        "IL" => "ILLINOIS",
                                        "IN" => "INDIANA",
                                        "IA" => "IOWA",
                                        "KS" => "KANSAS",
                                        "KY" => "KENTUCKY",
                                        "LA" => "LOUISIANA",
                                        "ME" => "MAINE",
                                        "MH" => "MARSHALL ISLANDS",
                                        "MD" => "MARYLAND",
                                        "MA" => "MASSACHUSETTS",
                                        "MI" => "MICHIGAN",
                                        "MN" => "MINNESOTA",
                                        "MS" => "MISSISSIPPI",
                                        "MO" => "MISSOURI",
                                        "MT" => "MONTANA",
                                        "NE" => "NEBRASKA",
                                        "NV" => "NEVADA",
                                        "NH" => "NEW HAMPSHIRE",
                                        "NJ" => "NEW JERSEY",
                                        "NM" => "NEW MEXICO",
                                        "NY" => "NEW YORK",
                                        "NC" => "NORTH CAROLINA",
                                        "ND" => "NORTH DAKOTA",
                                        "MP" => "NORTHERN MARIANA ISLANDS",
                                        "OH" => "OHIO",
                                        "OK" => "OKLAHOMA",
                                        "OR" => "OREGON",
                                        "PW" => "PALAU",
                                        "PA" => "PENNSYLVANIA",
                                        "PR" => "PUERTO RICO",
                                        "RI" => "RHODE ISLAND",
                                        "SC" => "SOUTH CAROLINA",
                                        "SD" => "SOUTH DAKOTA",
                                        "TN" => "TENNESSEE",
                                        "TX" => "TEXAS",
                                        "UT" => "UTAH",
                                        "VT" => "VERMONT",
                                        "VI" => "VIRGIN ISLANDS",
                                        "VA" => "VIRGINIA",
                                        "WA" => "WASHINGTON",
                                        "WV" => "WEST VIRGINIA",
                                        "WI" => "WISCONSIN",
                                        "WY" => "WYOMING"
                                    );
                                    
                                    foreach ($states as $abbrev=>$state) {
                                        $current = ($profile['state'] ? $profile['state'] : SettingManager::GetSetting("Default State"));
                                        echo "<option value='$abbrev'" . ($current == $abbrev ? " selected='selected'" : "") . ">$state</option>";
                                    }
                                    echo "</select>";
                        ?>					
                        </td>
                    </tr>
                    <tr>
                        <td>ZIP</td>
                        <td><input type='text' name='zip' value="<? echo $profile['zip']; ?>" /></td>
                    </tr>
                    <tr>
                        <td>Office Phone Number</td>
                        <td><input type='text' name='office_phone' value="<? echo $profile['office_phone']; ?>" /></td>
                    </tr>
                    <tr>
                        <td>Cell Phone Number</td>
                        <td><input type='text' name='cell_phone' value="<? echo $profile['cell_phone']; ?>" /></td>
                    </tr>
                    <tr>
                        <td>E-Mail</td>
                        <td><? echo $profile['email']; ?></td>				
                    </tr>
                    <tr>
                        <td>Website</td>
                        <td><input type='text' name='website' value='<? echo $profile['website']; ?>' /></td>
                    </tr>
                    <tr>
                        <td>Other Information</td>
                        <td><textarea name='other' style='width:95%; height:200px;'><?php echo stripslashes($profile['other']); ?></textarea></td>
                    </tr>
                    <tr>
                        <td colspan='3'><input type='submit' value='Save' /><input type='reset' value='Cancel' onClick='history.back(-1)' /></td>				
                    </tr>
                </table>
                </form>
                <?php
            }
		}
		else {
			ErrorMessage::Show("Error","You don't have a profile to edit");
		}
		Functions::PrintFooter();
	}
	else if ($_GET['id']) {
		$query = "SELECT * FROM guests JOIN landlords ON landlords.accountid = guests.id WHERE guests.id = " . $_GET['id'] . ";";
		$res = DBM::FetchRow($query);
		
		Functions::PrintHeader("View Profile");
		
		// verify permission
		if (! (AuthManager::AuthLevelMatches(array(AuthConstants::STUDENTS,AuthConstants::GUESTS,AuthConstants::ADMINISTRATORS)) || ($res['accountid'] != AuthManager::GetUserID())) ) {
            ErrorMessage::Show("Permissions Error","Sorry, You don't have permission to view this profile.");
		}
		else if (is_array($res)) {
			?>
			<table class='wide cgltable'>
				<tr>
					<th colspan='3'>Profile</th>
				</tr>
				<tr>
					<td rowspan='6' style='width:300px;'>
						<?php
							$thumb = new Thumbnail("listingimages/landlords/" . $_GET['id'] . ".png",300,NULL);
							$thumb->Render();
						?>
					</td>
					<td style='width:200px;'>Landlord Name</td>
					<td><?php echo $res['name']; ?></td>
				</tr>
				<tr>
					<td>Address</td>
					<td><?php 
						$addr = new AddrString($res,true);
						$addr->Render();
					?></td>
				</tr>
				<tr>
					<td>Phone #</td>
					<td><?php
						echo "<b>Office Phone</b>: ";
						if (!empty($res['office_phone'])) {
							echo $res['office_phone'];
						}
						else echo "<i>unspecified</i>";
						echo "<br />";
						
						echo "<b>Cell Phone</b>: ";
						if (!empty($res['cell_phone'])) {
							echo $res['cell_phone'];
						}
						else echo "<i>unspecified</i>";
						
						echo "<br />";
					?></td>
				</tr>
				<tr>
					<td>E-Mail</td>
					<td>
						<?php if (!empty($res['email'])) { ?>
						<a href='mailto:<?php echo $res['email']; ?>'><?php echo $res['email']; ?></a>
						<?php } else { ?>
						<i>unspecified</i>
						<?php } ?>
					</td>
				</tr>
				<tr>
					<td>Website</td>
					<td>
						<?php if (!empty($res['website'])) { ?>
						<a href='<?php echo $res['website']; ?>'><?php echo $res['website']; ?></a>
						<?php } else { ?>
						<i>unspecified</i>
						<?php } ?>						
					</td>
				</tr>
				<tr>
                    <td>Other&nbsp;Information</td>
                    <td><?=str_replace("\n","<br />",stripslashes($res['other']))?></td>
				</tr>
			</table>
			<?php
		}
		else InfoMessage::Show("Sorry","Sorry, that landlord hasn't created a profile.  There is currently no way to contact this landlord.");
		
		$query = "SELECT * FROM listings WHERE landlordid=" . $_GET['id'] . ";";
		$listings = DBM::FetchAllRows($query);
		
		echo "<br /><br />";
		echo "<h4>Listings</h4>";
		
		if (count($listings) == 0) {
			InfoMessage::Show("No Listings", "This landlord doesn't have any listings.");
		}
		else {
			echo "<table class='wide cgltable'>";
			echo "<tr>" .
					"<th style='width:100px;'>Listing ID</th>" .
					"<th>Address</th>" .
					"<th>&nbsp;</th>" .
				"</tr>";
			foreach ($listings as $listing) {
				echo "<tr>";
				$listingobj = ListingManager::FetchListing($listing['id']);
					echo "<td>" . $listingobj->GetID() . "</td>" .
						"<td>" . $listingobj->GetAddress() . "</td>" .
						"<td>" . 
						"<a href='listing.php?action=view&id=" . $listingobj->GetID() . "'>view listing</a>" . 
						"</td>";
				echo "</tr>";
			}
			
			echo "</table>";
		}
		

		
		Functions::PrintFooter();
	}
	else {
		Functions::PrintHeader("Profiles");
		ErrorMessage::Show("Error","You can't access a list of all landlords.");
		Functions::PrintFooter();
	}
?>
